package com.example.helloworldtext2.components;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.example.helloworldtext2.R;
//自定义组件
public class CUserAvatar extends LinearLayout {
    private ImageView userAvatar;
    private TextView nickname;

    public CUserAvatar(Context context) {
        super(context);
    }

    public CUserAvatar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(attrs);
    }

    public CUserAvatar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(attrs);
    }

    private void initView(AttributeSet attributeSet) {
        LayoutInflater.from(getContext()).inflate(R.layout.c_user_avatar, this);
        TypedArray array = getContext().obtainStyledAttributes(attributeSet, R.styleable.CUserAvatar);

        userAvatar = findViewById(R.id.userAvatar);
        userAvatar.setImageDrawable(array.getDrawable(R.styleable.CUserAvatar_userAvatar));

        nickname = findViewById(R.id.nickname);
        nickname.setText(array.getText(R.styleable.CUserAvatar_nickname));

        array.recycle();
    }
    
    // 动态设置用户头像
    public void setUserAvatar(int drawableResId) {
        if (userAvatar != null) {
            userAvatar.setImageResource(drawableResId);
        }
    }
    
    // 动态设置用户头像（使用Drawable对象）
    public void setUserAvatar(Drawable drawable) {
        if (userAvatar != null) {
            userAvatar.setImageDrawable(drawable);
        }
    }
    
    // 动态设置用户昵称
    public void setNickname(String nicknameText) {
        if (nickname != null) {
            nickname.setText(nicknameText);
        }
    }
    
    // 获取用户头像ImageView
    public ImageView getUserAvatarView() {
        return userAvatar;
    }
    
    // 获取昵称TextView
    public TextView getNicknameView() {
        return nickname;
    }
}